<?php
#+------------------------------------------------------------------
#| 普通的。
#+------------------------------------------------------------------
#| Author:Janmas Cromwell <janmas-cromwell@outlook.com>
#+------------------------------------------------------------------
namespace app\library\websocket\logic;

use app\library\redis\Redis;
use app\library\websocket\tool\Package;
use timestamp\TimeStamp;

class Messages
{
	const PREFIX = 'message_';

	static function create(Package $package, string $sender)
	{
        $message = $package->toArray();
        $message['from'] = $sender;
        echo "消息存储";
        $redis = Redis::get();
        $msgId = self::PREFIX . $message['msg_id'];
        if ($message['action'] != 'text') {
            $message['link'] = $message['data']['url'];
            $message['data'] = json_encode($message['data']);
        }

        foreach ($message as $key => $value) {
            if (!$redis->hSet($msgId, $key, $value)) {
                return false;
            }
        }

        Sessions::add($message['chat_id'], $msgId);
        Redis::put($redis);
        return $msgId;
    }

    static function get(string $msgId, string $field = '*')
    {

        $redis = Redis::get();
        if ($field == '*') {
            $res = $redis->hGetAll($msgId);
            if ($res['action'] != 'text') {
                $res['data'] = json_decode($res['data'], true);
            }
            $res['sender'] = Users::getUserById($res['from']);
            $res['receiver'] = Users::getUserById($res['to']);
            $res['time'] = (new TimeStamp($res['timestamp']))->friendly();
        } else {
            if ($field == 'data') {
                $action = $redis->hGet(self::PREFIX . $msgId, 'action');
                if ($action == 'audio') {
                    $res = '[语音]';
                } elseif ($action == 'image_text') {
                    $res = '[图片]' . $redis->hGet(self::PREFIX . $msgId, $field);
                } elseif ($action == 'image') {
                    $res = '[图片]';
                } else {
                    $res = $redis->hGet(self::PREFIX . $msgId, $field);
                }
			} else {
				$res = $redis->hGet(self::PREFIX . $msgId, $field);
			}
		}
		Redis::put($redis);
		return $res;
	}

	static function read(string $msgId, string $userId)
	{
		$redis = Redis::get();
		$res = $redis->hSet($msgId, 'is_read', 1);
		$sessionId = $redis->hGet($msgId, 'chat_id');
		Sessions::read($sessionId, $userId);
		Redis::put($redis);
		return $res;
	}

	static function remove(string $msgId, string $userId)
	{
		$redis = Redis::get();
		$sender = $redis->hGet(self::PREFIX . $msgId, 'from');
		if ($sender == $userId) {
			$res = $redis->hSet(self::PREFIX . $msgId, 'user_del', 1);
		} else {
			$res = $redis->hSet(self::PREFIX . $msgId, 'to_del', 1);
		}
		Redis::put($redis);
		return $res;
	}
}
